package Image;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * description:在图片上写字
 * author:zcx
 * lenovo
 * 时间：2022.01.23.19.38
 */
public class Img5 {
    public static void main(String[] args) throws IOException {
              var w=800;
              var h=800;
              var t=2;
              var i=new BufferedImage(w,h,t);
              var g=i.createGraphics();
              //
              g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
              g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
              //g.setStroke(new BasicStroke(5));
        //画布颜色
              g.setColor(Color.PINK);
              g.fillRect(0,0,w,h);

//文本字符串
        var r=new Random();
        String text="hello world 中文字符串";
        int x=50;
        int y=100;
        g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256),r.nextInt(256)));
        var font=new Font("宋体",Font.BOLD,50);
        g.setFont(font);
        var fm=g.getFontMetrics(font);
        var tw=fm.stringWidth(text);
       //左上角
        int sp=10;
        x=sp+0;
        y=sp+fm.getAscent()-fm.getDescent();
        //中间
        x=w/2-tw/2;
        y=h/2+(fm.getAscent()-fm.getDescent())/2;
        //底部水平中央
        x=w/2-tw/2;
        y=h-sp-fm.getDescent();
        //右上角
        x=w-tw-sp;
        y=sp+fm.getAscent()-fm.getDescent();
       //右下角
        x=w-tw-sp;
        y=h-sp;
        //g.drawString("YYY",x,y);


        //随机位置
        x=r.nextInt(sp,w-tw-sp);
        y=r.nextInt(sp+fm.getAscent()-fm.getDescent(),h-sp-fm.getDescent());
         g.drawString(text,x,y);

              g.dispose();
              ImageIO.write(i,"png",new File("i3.png"));

    }
}
